from utils.common import *
from pydantic import BaseModel,Field,validator
from typing import Optional
from fastapi import APIRouter
from config.redis import REDIS_POOL
from config.db import db

from utils.result import *

import redis,os,hashlib

loginIn = APIRouter()

class Admin(BaseModel):
    username: str = Field(description="用户名")
    password: str = Field(description="密码")
    @validator('username')
    def username_validator(cls, value):
        if not  value:
            raise ValueError("用户名不能为空")
    @validator('password')
    def password_validator(cls, value):
        if not  value:
            raise ValueError("密码不能为空")
@loginIn.get("/login",summary=['登录'])
async def login(username:  Optional[str]=None, password:  Optional[str]=None):
    if not username:
        raise ValueError("用户名不能为空")
    if not password:
        raise ValueError("密码不能为空")

    os.getenv('AUTH_SOLT')
    pwd = password+os.getenv('AUTH_SOLT')
    md5_hash  = hashlib.md5()
    md5_hash.update(pwd.encode("utf-8"))
    admin = db("select id,user_name from for_admin where user_name = %s and password = %s ",[username,md5_hash.hexdigest(),])
    if not admin:
        return error('用户名或密码错误')
    token = for_generate_random_string(32)
    rds = redis.Redis(connection_pool=REDIS_POOL)
    rds.setex(username, 86400, token)
    return success({'token':token})
    # sql = "select * from user where id = %s"
    # params = [id]
    # result = db(sql, params)
    # if result:
    #     return result[0]
    # else:
    #     return None